package com.llan;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by llan on 2018/5/2320:45.
 */
public class HystrixFailsSilently extends HystrixCommand<List<String>> {

    private final boolean throwException;

    public HystrixFailsSilently(boolean throwException) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.throwException = throwException;
    }

    @Override
    protected List<String> run() {
        if (throwException) {
            // 模拟出现异常,以便触发降级逻辑
            throw new RuntimeException("failure from HystrixFailsSilently");
        } else {
            // 模拟正常逻辑
            ArrayList<String> values = new ArrayList<String>();
            values.add("success");
            return values;
        }
    }

    @Override
    protected List<String> getFallback() {

        // 触发降级,返回空null
        return null;
        // 触发降级,返回空List
//        return Collections.emptyList();
    }

    public static class UnitTest {

        @Test
        public void testSuccess() {
            // 单元测试正常逻辑执行
            assertEquals("success", new HystrixFailsSilently(false).execute().get(0));
        }

        @Test
        public void testFailure() {
            try {
                // 单元测试异常逻辑,返回list元素个数
                assertEquals(0, new HystrixFailsSilently(true).execute().size());
            } catch (HystrixRuntimeException e) {
                fail("we should not get an exception as we fail silently with a fallback");
            }
        }
    }
}